//
//  HistoryUITest.swift
//  LoopUITests
//
//  Created by thomas on 2020/9/23.
//

import XCTest
@testable import Loop

class HistoryUITest: XCTestCase {

    var app: XCUIApplication!

    override func setUpWithError() throws {

        continueAfterFailure = false

        app = XCUIApplication()
        app.launch()
    }

    override func tearDownWithError() throws {
    }

    func testDisplayHistoryTable() throws {

        app.tabBars.buttons["History"].tap()

        let tableView = app.tables.firstMatch
        XCTAssertNotNil(tableView)
    }

    func testNoNewRequestFlagJustAppeared() throws {

        app.tabBars.buttons["History"].tap()

        XCTAssertEqual(app.navigationBars.firstMatch.buttons.count, 0)
    }

    func testLastRequestCellIsSpecial() throws {

        let expectation = self.expectation(description: "testLastRequestCellIsSpecial")
        DispatchQueue.main.asyncAfter(deadline: .now() + 6) {

            self.app.tabBars.buttons["History"].tap()

            let tableView = self.app.tables.firstMatch
            XCTAssertNotNil(tableView)
            XCTAssertEqual(tableView.cells.firstMatch.images.count, 1)

            expectation.fulfill()
        }

        self.waitForExpectations(timeout: 10, handler: nil)
    }

    func testPulldownToRefresh() throws {

        let expectation = self.expectation(description: "testPulldownToRefresh")
        DispatchQueue.main.asyncAfter(deadline: .now() + 10) {

            XCUIApplication().tabBars.buttons["History"].tap()

            let tableView = self.app.tables.firstMatch
            XCTAssertNotNil(tableView)
            let count = tableView.cells.count

            DispatchQueue.main.asyncAfter(deadline: .now() + 10) {

                tableView.swipeDown()
                // FIXME: 此处本应该使用XCTAssertGreaterThan，但是由于UITableViewController
                // 默认的refreshControl的触发距离比较大，导致此处调用swipeDown并不会触发tableview
                // 的下拉刷新，所以tableview并不会加载新数据。后期应该引入第三方下拉刷新库来解决这个问题
                XCTAssertGreaterThanOrEqual(tableView.cells.count, count)

                expectation.fulfill()
            }
        }

        self.waitForExpectations(timeout: 25, handler: nil)
    }

    func testShowNewRequestFlagAfterNewRecordInserted() throws {

        let expectation = self.expectation(description: "testShowNewRequestFlag")
        DispatchQueue.main.asyncAfter(deadline: .now() + 10) {

            XCUIApplication().tabBars.buttons["History"].tap()

            DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
                XCTAssertEqual(self.app.navigationBars.firstMatch.buttons.count, 1)

                expectation.fulfill()
            }
        }

        self.waitForExpectations(timeout: 20, handler: nil)
    }
}
